import serial
import time
import csv

# 配置参数
SERIAL_PORT = '/dev/ttyUSB0'       # 替换为你的串口号
BAUDRATE = 115200          # 根据设备设置波特率
RECORD_INTERVAL = 0.1      # 记录间隔(秒)
OUTPUT_FILE = 'iq_data.csv' # 输出文件名

def parse_iq_value(raw_data):
    """从串口数据中解析出IQ值"""
    try:
        # 示例1：如果数据是 "IQ:1.234\r\n"
        if 'IQ:' in raw_data:
            return float(raw_data.strip().split(':')[1])
        
        # 示例2：如果数据是纯数字 "1.234\r\n"
        return float(raw_data.strip())
    except:
        return None  # 解析失败

def main():
    # 初始化串口
    ser = serial.Serial(SERIAL_PORT, BAUDRATE, timeout=0.1)
    print(f"开始记录IQ数据到 {OUTPUT_FILE}...")
    
    # 创建CSV文件并写入表头
    with open(OUTPUT_FILE, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(['Time(s)', 'IQ_Value'])  # 修改表头为时间（秒）和IQ值
        
        try:
            elapsed_time = 0.0  # 初始化时间为0
            while True:
                start_time = time.time()
                
                # 读取串口数据
                raw_data = ser.readline().decode('ascii', errors='ignore')
                
                if raw_data:
                    iq_value = parse_iq_value(raw_data)
                    if iq_value is not None:
                        # 写入数据
                        writer.writerow([f"{elapsed_time:.1f}", iq_value])
                        print(f"记录: {elapsed_time:.1f}s | IQ: {iq_value:.4f}")
                
                # 精确控制采集间隔
                elapsed = time.time() - start_time
                if elapsed < RECORD_INTERVAL:
                    time.sleep(RECORD_INTERVAL - elapsed)
                
                # 增加时间
                elapsed_time += RECORD_INTERVAL
                    
        except KeyboardInterrupt:
            print("\n记录终止")
        finally:
            ser.close()

if __name__ == '__main__':
    main()